package com.quickcancellation.crm.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quickcancellation.crm.config.LogAspect;
import com.quickcancellation.crm.pojo.dto.PageDto;
import com.quickcancellation.crm.pojo.dto.PageParamsDto;
import com.quickcancellation.crm.pojo.dto.ResponseDto;
import com.quickcancellation.crm.pojo.entity.Productitem;
import com.quickcancellation.crm.pojo.entity.Stock;
import com.quickcancellation.crm.pojo.entity.Stockdetail;
import com.quickcancellation.crm.service.IProductitemService;
import com.quickcancellation.crm.service.IStockService;
import com.quickcancellation.crm.service.IStockdetailService;
import com.quickcancellation.crm.service.IUserinfoService;
import com.quickcancellation.crm.utils.DateUtils;
import com.quickcancellation.crm.utils.PageUtils;
import com.quickcancellation.crm.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-03-04
 */

@CrossOrigin
@RestController
@SaCheckLogin
@Api(tags = "库存控制")
@SaCheckRole("stock")
@RequestMapping("/stock")
public class StockController {

    @Resource
    private IStockService stockService;

    private final static Logger logger = LoggerFactory.getLogger(StockController.class);

    private final Object lock = new Object();

    @Resource
    private HttpServletRequest request;


    @Resource
    private IProductitemService productitemService;

    @Resource
    private IStockdetailService stockdetailService;
    private int num = 1;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private IUserinfoService userinfoService;


    @PostMapping("add")
    @LogAspect()
    @ApiOperation("库存管理")
    @Transactional
    public synchronized ResponseDto list() {

        synchronized (lock) {

            logger.info("操作:" + num + "开始");
            Stock stock = stockService.getOne(new QueryWrapper<Stock>().eq("productCode", "B0000002"));

            Integer stockBatch = stock.getStockBatch();

            logger.info("********当前库存为:【" + stockBatch + "】箱");

            if (stockBatch <= 0) {
                return ResponseUtil.fail("库存不足");
            }

            logger.info("********库存扣减后:【" + (stockBatch - 20) + "】箱");

            QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("productCode", stock.getProductCode());
            queryWrapper.eq("stockBatch", stock.getStockBatch());
            queryWrapper.eq("id", stock.getId());
            stock.setStockBatch(stockBatch - 20);

            boolean result = stockService.update(stock, queryWrapper);
            if (result) {
                Stock s1 = new Stock();
                s1.setStockSingle(stockBatch);
                s1.setStockBatch(20);
                s1.setUpdateTime(String.valueOf(num));
                num++;
                stockService.save(s1);
            }
            logger.info("操作:" + num + "结束");
        }
        return ResponseUtil.success();
    }


    @PostMapping("list")
    @LogAspect()
    @ApiOperation("库存列表")
    public ResponseDto list(@RequestBody PageParamsDto<Map> params) {
        PageDto<Map> pageDto = PageUtils.getPageParams(params);

        List<Map> list = stockService.getStockList(pageDto);
        Long count = stockService.getStockListCount(pageDto);


        return ResponseUtil.success(count, list);

    }

    @PostMapping("productItem3List")
    @LogAspect()
    @ApiOperation("品规列表")
    public ResponseDto product3List(@RequestBody PageParamsDto<Map> params) {

        List<Productitem> list = productitemService.list(
                new QueryWrapper<Productitem>()
                        .eq("itemType", 3)
                        .select("classGuid", "itemName")
        );

        return ResponseUtil.success(list);
    }

    @PostMapping("getStockDetails")
    @LogAspect()
    @ApiOperation("获取库存明细")
    public ResponseDto getStockDetail(@RequestBody Map<String, Object> params) {

        String agDisId = MapUtils.getString(params, "inDisAgId");

        String productCode = MapUtils.getString(params, "productCode");

        List<Map> list = stockdetailService.getStockDetails(agDisId, productCode);

        return ResponseUtil.success(list);
    }


    @PostMapping("getAgentDisList")
    @LogAspect()
    @ApiOperation("获取所有经销商中间商数据")
    public ResponseDto getAgentDisList() {

        // 简化开发不用mapper
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList("select  agentCode, agentName from cu_v_agentdistributor");

        return ResponseUtil.success(resultList);

    }

    @PostMapping("getProductList")
    @LogAspect()
    @ApiOperation("获取所有经销商中间商数据")
    public ResponseDto getProductList() {

        String sql = "select productCode,productName from pd_t_product";
        List<Map<String, Object>> productList = jdbcTemplate.queryForList(sql);

        return ResponseUtil.success(productList);

    }


    @PostMapping("saveStockAdd")
    @LogAspect()
    @ApiOperation("保存库存增加(管理员手动添加)")
    @Transactional
    public ResponseDto saveStockAdd(@RequestBody Map params) throws Exception {


        String agentCode = MapUtils.getString(params, "agentCode");
        String productCode = MapUtils.getString(params, "productCode");
        Integer stockBatch = MapUtils.getInteger(params, "stockBatch");
        boolean returnResult = false;

        // 判断是中间商还是经销商
        String sql = "select type from cu_v_agentdistributor where agentCode = '" + agentCode + "'";
        Map<String, Object> result = jdbcTemplate.queryForMap(sql);

        String type = MapUtils.getString(result, "type");

        sql = "select id from cu_v_agentdistributor where agentCode = '" + agentCode + "' and type = '" + type + "'";

        result = jdbcTemplate.queryForMap(sql);

        String agDisId = MapUtils.getString(result, "id");

        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("agDisId", agDisId);
        queryWrapper.eq("productCode", productCode);
        queryWrapper.eq("agDisType","ag".equals(type) ? 1 : 2);

        Stock stock = stockService.getOne(queryWrapper);


        String userId = userinfoService.getUserInfoByRequest(request).getId();


        // 如果本身已经存在库存
        if (stock != null) {
            Integer leftBatch = stock.getStockBatch();

            stock.setStockBatch(stockBatch + leftBatch);

            stock.setUpdateTime(DateUtils.getNow());

            stock.setUpdateOp(userId);

            returnResult = stockService.updateById(stock);

        } else {

            // 库存不存在 创建一条新的库存
            Stock newStock = new Stock();

            newStock.setStockBatch(stockBatch);
            newStock.setUpdateTime(DateUtils.getNow());
            newStock.setUpdateOp(userId);
            newStock.setAgDisId(agDisId);
            newStock.setProductCode(productCode);
            newStock.setStockSingle(0);
            newStock.setAgDisType("ag".equals(type) ? 1L : 2L);
            returnResult = stockService.save(newStock);
        }

        // 保存变动明细
        if (returnResult){
            Stockdetail stockdetail = new Stockdetail();
            stockdetail.setType(1);
            stockdetail.setProductCode(productCode);
            stockdetail.setSingleCount(0);
            stockdetail.setBatchCount(stockBatch.longValue());
            stockdetail.setCreateTime(DateUtils.getNow());
            stockdetail.setCreateOp(userId);
            stockdetail.setOrderCode("");
            stockdetail.setStockType(5);
            stockdetail.setRemark("正常入库");
            stockdetail.setAuditType(3);
            stockdetail.setInDisAgId(Long.valueOf(agDisId));
            stockdetail.setOutDisAgId(null);

            returnResult = stockdetailService.save(stockdetail);
        }else{
            throw new Exception("库存保存失败");
        }


//        stockdetailService.save()

        if (returnResult){
            return ResponseUtil.success();
        }else{
            throw new Exception("库存保存失败");
        }

    }

}
